package com.lw.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LW
 * @2020/8/22 10:36
 */
//lock锁与synchronized锁的“细节”差别
public class ReentrantLock2 {
    public static void main(String[] args) {
        Phone5 phone5 = new Phone5();

        new Thread(() -> {
            phone5.sendSms();
        }, "a").start();

        new Thread(() -> {
            phone5.sendSms();
        }, "b").start();
    }
}

class Phone5{
    Lock lock = new ReentrantLock();
    public void sendSms(){
        lock.lock();
        lock.lock();
        /**细节问题：
         * lock.lock();和lock.unlock();必须配对//否则会死在里面
         *
         */
        try {
            System.out.println(Thread.currentThread().getName()+"发短信");
            call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //加了两把锁必须配两个解锁
            lock.unlock();
            lock.unlock();
        }

    }
    public void call(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"打电话");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
